"""
文本统计程序 - v0.3版本
扩展功能：统计代码行、空行、注释行
"""

import sys
import re

def count_characters(text):
    """统计字符数（包括空格和标点）"""
    return len(text)

def count_words(text):
    """统计单词数"""
    words = re.findall(r'\b[a-zA-Z]+\b', text)
    return len(words)

def count_sentences(text):
    """统计句子数"""
    sentences = re.split(r'[.!?]+', text)
    sentences = [s.strip() for s in sentences if s.strip()]
    return len(sentences)

def count_code_lines(lines):
    """统计代码行数（非空行且非注释行）"""
    code_lines = 0
    for line in lines:
        stripped_line = line.strip()
        if stripped_line and not stripped_line.startswith('#'):
            code_lines += 1
    return code_lines

def count_empty_lines(lines):
    """统计空行数"""
    empty_lines = 0
    for line in lines:
        if not line.strip():
            empty_lines += 1
    return empty_lines

def count_comment_lines(lines):
    """统计注释行数"""
    comment_lines = 0
    for line in lines:
        stripped_line = line.strip()
        if stripped_line.startswith('#'):
            comment_lines += 1
    return comment_lines

def read_file_lines(filename):
    """读取文件内容为行列表"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return file.readlines()
    except FileNotFoundError:
        print(f"错误：文件 {filename} 未找到")
        return None
    except Exception as e:
        print(f"读取文件时出错：{e}")
        return None

def read_file_text(filename):
    """读取文件内容为字符串"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误：文件 {filename} 未找到")
        return None
    except Exception as e:
        print(f"读取文件时出错：{e}")
        return None

def main():
    if len(sys.argv) < 3:
        print("用法: python wc_advanced.py [参数] [文件名]")
        print("基础参数:")
        print("  -c  统计字符数")
        print("  -w  统计单词数")
        print("  -s  统计句子数")
        print("  -a  统计所有基本信息")
        print("扩展参数:")
        print("  -cl 统计代码行数")
        print("  -el 统计空行数")
        print("  -ml 统计注释行数")
        print("  -all 统计所有信息")
        return
    
    param = sys.argv[1]
    filename = sys.argv[2]
    
    if param in ['-cl', '-el', '-ml', '-all']:
        # 需要行级别的统计
        lines = read_file_lines(filename)
        if lines is None:
            return
        
        text = ''.join(lines)
    else:
        # 只需要文本内容
        text = read_file_text(filename)
        if text is None:
            return
        lines = text.split('\n')
    
    if param == '-c':
        char_count = count_characters(text)
        print(f"字符数: {char_count}")
    
    elif param == '-w':
        word_count = count_words(text)
        print(f"单词数: {word_count}")
    
    elif param == '-s':
        sentence_count = count_sentences(text)
        print(f"句子数: {sentence_count}")
    
    elif param == '-cl':
        code_line_count = count_code_lines(lines)
        print(f"代码行数: {code_line_count}")
    
    elif param == '-el':
        empty_line_count = count_empty_lines(lines)
        print(f"空行数: {empty_line_count}")
    
    elif param == '-ml':
        comment_line_count = count_comment_lines(lines)
        print(f"注释行数: {comment_line_count}")
    
    elif param == '-a':
        char_count = count_characters(text)
        word_count = count_words(text)
        sentence_count = count_sentences(text)
        
        print(f"字符数: {char_count}")
        print(f"单词数: {word_count}")
        print(f"句子数: {sentence_count}")
    
    elif param == '-all':
        char_count = count_characters(text)
        word_count = count_words(text)
        sentence_count = count_sentences(text)
        code_line_count = count_code_lines(lines)
        empty_line_count = count_empty_lines(lines)
        comment_line_count = count_comment_lines(lines)
        
        print("=== 文本统计报告 ===")
        print(f"字符数: {char_count}")
        print(f"单词数: {word_count}")
        print(f"句子数: {sentence_count}")
        print(f"代码行数: {code_line_count}")
        print(f"空行数: {empty_line_count}")
        print(f"注释行数: {comment_line_count}")
        print(f"总行数: {len(lines)}")
    
    else:
        print("错误：无效参数")
        print("可用参数: -c, -w, -s, -cl, -el, -ml, -a, -all")

if __name__ == "__main__":
    main()